package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"novel_website/models"
	"os"
	"path"
	"strings"
)

type BookController struct {
	beego.Controller
}

func (c *BookController) Create() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	var book models.Book
	book.BookTitleImage = c.GetString("image_url")
	book.BookTitle = c.GetString("title")
	book.BookAuthorId, _ = c.GetInt("author")
	if book.CreateBook() != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "上传成功",
	}
	c.ServeJSON()
}
func (c *BookController) InputImage() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	file, m, err := c.GetFile("image")
	if err != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙,图片上传失败",
		}
		c.ServeJSON()
		return
	}
	if m.Size > 2<<20 {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "图片过大",
		}
		c.ServeJSON()
		return
	}
	PathStr := ".jpg.jpeg.png"
	if !(strings.Contains(PathStr, path.Ext(m.Filename))) {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "格式错误",
		}
		c.ServeJSON()
		return
	}
	openFile, err := os.OpenFile("./static/img/"+m.Filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
	if err != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙,图片上传失败",
		}
		c.ServeJSON()
		return
	}
	io.Copy(openFile, file)
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "上传成功",
		"Data": "http://127.0.0.1:8080/static/img/" + m.Filename,
	}
	c.ServeJSON()
	return
}
func (c *BookController) ReadLogsList() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	page, _ := c.GetInt("page", 1)
	limit, _ := c.GetInt("limit", 10)
	id, _ := c.GetInt("id")
	key := fmt.Sprintf("id=%d;limit=%d;page=%d", id, limit, page)
	var books_list []struct {
		models.Book
		Type string
	}
	JsonGet, _ := models.Rdb.Get(models.Ctx, key).Result()
	if JsonGet != "" {
		json.Unmarshal([]byte(JsonGet), &books_list)
	} else {
		if models.DB.Model(&models.Book{}).Joins("join read_logs on read_logs.book_id = books.id").Where("read_logs.user_id = ?", id).Select("books.*,read_logs.type").Limit(limit).Offset((page-1)*limit).Scan(&books_list).Error != nil {
			c.Data["json"] = map[string]any{
				"Code": 500,
				"Msg":  "服务器繁忙",
			}
			c.ServeJSON()
			return
		}
		JsonSet, _ := json.Marshal(&books_list)
		models.Rdb.Set(models.Ctx, key, JsonSet, 0)
	}
	var toapo int
	models.DB.Model(&models.ReadLog{}).Where("user_id = ?", id).Pluck("count(*)", &toapo)
	c.Data["json"] = map[string]any{
		"Code":  200,
		"Msg":   "查询成功",
		"Data":  books_list,
		"Total": toapo,
	}
	c.ServeJSON()
	return
}
func (c *BookController) DelReadLog() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	book_id, _ := c.GetInt("bId")
	user_id, _ := c.GetInt("uId")
	var log models.ReadLog
	models.DB.Where("book_id=? and user_id = ?", book_id, user_id).Limit(1).Find(&log)
	if log.Type == "" {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "记录已删除或不存在",
		}
		c.ServeJSON()
		return
	}
	if log.Type == "读完" {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "已完成的记录不可删除",
		}
		c.ServeJSON()
		return
	}
	models.DB.Where("book_id=? and user_id = ?", book_id, user_id).Delete(&log)
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "删除成功",
	}
	c.ServeJSON()
}
